from rest_framework.permissions import BasePermission
from apps.teachers.models import Teacher
from apps.courses.models import Course
from apps.students.models import Student
from apps.classes.models import Class
from apps.classmembers.models import StudentClass

# 需要进行管理员鉴权的模型
STAFF_AUTHORIZE_MODEL = [Course, Student, Class, StudentClass]


# 自定义权限管理类 => 只允许已登录且是激活状态的用户访问视图
class CustomIsAuthenticated(BasePermission):
    def has_permission(self, request, view):
        return isinstance(request.user, Teacher) and request.user.is_active


# 自定义权限管理类 => 只允许管理员访问修改数据,其他用户只有访问权限
class CustomIsStaff(BasePermission):
    def has_permission(self, request, view):
        is_authenticated = CustomIsAuthenticated().has_permission(request, view)
        method = request.method
        access_model_class = view.get_queryset().model if hasattr(view, 'get_queryset') else None

        if not is_authenticated:
            return False

        # 访问需要鉴权的接口,且非管理员,拒绝访问
        if method != "GET" and access_model_class in STAFF_AUTHORIZE_MODEL and not request.user.is_staff:
            return False

        return True


# 自定义权限管理类 => 只允许超级管理员访问视图
class CustomIsSuperUser(BasePermission):
    def has_permission(self, request, view):
        return request.method == "GET" or CustomIsAuthenticated().has_permission(request,
                                                                                 view) and request.user.is_superuser
